package com.dcy.znoa.service.conference.impl;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.conference.model.conference.SelectConferenceModel;
import com.dcy.znoa.controller.publiz.model.messNotice.AddMessNoticeListAndMsgModel;
import com.dcy.znoa.dao.conference.ConferenceDao;
import com.dcy.znoa.dao.conference.ConferencePersonDao;
import com.dcy.znoa.dao.conference.ConferenceRoomDao;
import com.dcy.znoa.domain.conference.Conference;
import com.dcy.znoa.domain.conference.ConferencePerson;
import com.dcy.znoa.domain.conference.ConferenceRoom;
import com.dcy.znoa.domain.conference.ConferenceRoomAppointmentVo;
import com.dcy.znoa.domain.conference.ConferenceVo;
import com.dcy.znoa.domain.conference.MyNotFinishedConferenceVo;
import com.dcy.znoa.domain.conference.ReceiveConferenceDetailVo;
import com.dcy.znoa.domain.conference.ReceiveConferenceVo;
import com.dcy.znoa.service.conference.ConferenceService;
import com.dcy.znoa.service.publiz.MessNoticeService;

@Service
public class ConferenceServiceImpl implements ConferenceService {

	@Autowired
	ConferenceDao conferenceDao;
	
	@Autowired
	ConferencePersonDao conferencePersonDao; 
	
	@Autowired
	ConferenceRoomDao conferenceRoomDao;
	
	@Autowired
    MessNoticeService messNoticeService;
	
	@Override
	public JsonForList selectList(SelectConferenceModel model) throws InvocationTargetException, IllegalAccessException {
		List<ConferenceVo> list = conferencePersonDao.selectConferenceList(model);		
		
		EntityWrapper<Conference> ew = new EntityWrapper<>();
        ew.eq("comp_id", model.getCompId());
        ew.eq("valid_flag", 1);
        
        Integer total = conferenceDao.selectCount(ew);	
		
		return new JsonForList(list, total);	
	}

	@Override
	public JsonCommon insert(Conference conference,Long[] operIds) throws InvocationTargetException, IllegalAccessException, BusinessException, ClientException {
        //会议时间不能重复  
		String startTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(conference.getStartTime());
		String endTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(conference.getEndTime());
		EntityWrapper<Conference> ew = new EntityWrapper<>();
        ew.eq("confer_id", conference.getConferId());
        ew.eq("valid_flag", 1);      
        ew.andNew("start_time between {0} and {1}", startTimeStr,endTimeStr)
          .or("end_time between {0} and {1}", startTimeStr,endTimeStr);

        Integer total = conferenceDao.selectCount(ew);	
        if (total != null && total > 0) {
            return new JsonCommon("404","会议时间有重复");
        }				
		
        Integer result = conferenceDao.insert(conference);
        if (result == null || result <= 0) {
            return new JsonCommon(JsonCommon.INSERT_ERROR_CODE);
        }
        Date createTime = new Date();
        for (Long operId : operIds) {
        	EntityWrapper<ConferencePerson> ewConferencePerson = new EntityWrapper<>();
        	ewConferencePerson.eq("conf_id", conference.getConfId());
        	ewConferencePerson.eq("oper_id", operId);
        	ewConferencePerson.eq("valid_flag", 1);            
            Integer totalConferencePerson = conferencePersonDao.selectCount(ewConferencePerson);
            if (totalConferencePerson != null && totalConferencePerson.intValue() > 0) {
            	continue;
			}
        	ConferencePerson conferencePerson = new ConferencePerson();
        	conferencePerson.setConfId(conference.getConfId());
        	conferencePerson.setConferId(conference.getConferId());
        	conferencePerson.setOperId(operId);
        	conferencePerson.setReplyStatus(0);  //回执默认0
        	conferencePerson.setCreateOperName(conference.getCreateOperName());
        	conferencePerson.setCreateTime(createTime);
        	conferencePerson.setValidFlag(1);
        	
			conferencePersonDao.insert(conferencePerson);
		}
        
        AddMessNoticeListAndMsgModel amnlModel = new AddMessNoticeListAndMsgModel();
        amnlModel.setMessTitle("会议通知");
        amnlModel.setMessage("会议主题:"+conference.getConferSubject());
        amnlModel.setMessType(8);//会议
        amnlModel.setSendTime(conference.getCreateTime());
        amnlModel.setCreateOperId(conference.getCreateOperId());
        amnlModel.setCreateTime(conference.getCreateTime());
        amnlModel.setValidFlag(1);
        amnlModel.setIsSms(0);
        if (conference.getNotice()) {
        	amnlModel.setIsSms(1);
		}
        amnlModel.setOperIdsStr(toString(operIds));
        //ids
        amnlModel.setEntityId(conference.getConfId());
        amnlModel.setEntityTbl("conference");
        
        //给接收人的消息
        Long messId = messNoticeService.insertBatchAndMsg(amnlModel);
        
        return new JsonCommon(JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
	}

	@Override
	public JsonCommon cancelConference(Conference conference) {		
		Date updateTime = new Date();
		
		Conference conferenceOld = conferenceDao.selectById(conference.getConfId());
		if (conferenceOld.getEndTime().before(updateTime)) {
			return new JsonCommon("404","会议已经结束，不能取消");
		}
		
		Integer result = conferenceDao.updateById(conference);
		if (result == null || result <= 0) {
            return new JsonCommon(JsonCommon.INSERT_ERROR_CODE);
        }
		
		EntityWrapper<ConferencePerson> ew = new EntityWrapper<>();
		ew.setEntity(ConferencePerson.builder().confId(conference.getConfId()).build());
		List<ConferencePerson> list = conferencePersonDao.selectList(ew);
		if (null == list || list.isEmpty()) {
			return new JsonCommon(JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
		
		for (ConferencePerson conferencePerson : list) {
			conferencePerson.setUpdateOperName(conference.getUpdateOperName());
			conferencePerson.setUpdateTime(updateTime);
			conferencePerson.setValidFlag(0);
			conferencePersonDao.updateById(conferencePerson);
		}    
		
		//还要撤销预约记录=====================================
        return new JsonCommon(JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
	}

	@Override
	public JsonForList selectMyCreateConference(SelectConferenceModel selectConferenceModel) {
		List<Conference> list;       	        
        EntityWrapper<Conference> ew = new EntityWrapper<>();
        ew.eq("create_oper_id", selectConferenceModel.getCreateOperId());
        ew.eq("comp_id", selectConferenceModel.getCompId());
        ew.orderBy("create_time", false);
        list = conferenceDao.selectList(ew);	
        
        if (list.isEmpty()) {
			return new JsonForList(null, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		} else {
			return new JsonForList(list, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
	}
    
	@Override
	public JsonCommon myCreateConferenceDetail(Long confId) {       
        Conference conference = conferenceDao.selectById(confId);
        if (null != conference) {
			//查找参会人员数量
        	EntityWrapper<ConferencePerson> ew1 = new EntityWrapper<>();
    		ew1.eq("conf_id",conference.getConfId());  //会议ID
            
    		Integer operAmount = conferencePersonDao.selectCount(ew1);
    		conference.setOperAmount(operAmount);  
    		
    		ConferenceRoom conferenceRoom = conferenceRoomDao.selectById(conference.getConferId());
    		if (conferenceRoom != null) {
    			conference.setConferAddress(conferenceRoom.getConferAddress());
			}    		
    		return new JsonCommon(conference, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
		return new JsonCommon(null, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
	}

	@Override
	public JsonForList myReceiveConference(SelectConferenceModel model) {
		List<ReceiveConferenceVo> list = conferencePersonDao.selectMyReceiveConference(model.getCreateOperId());
		if (list.isEmpty()) {
			return new JsonForList(null, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		} else {
			return new JsonForList(list, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
	}

	@Override
	public JsonCommon myReceiveConferenceDetail(SelectConferenceModel model) {
		List<ReceiveConferenceDetailVo> list = conferencePersonDao.selectMyReceiveConferenceDetail(model);
		if (!list.isEmpty()) {
			ReceiveConferenceDetailVo receiveConferenceDetailVo =list.get(0);
			//查找参会人员数量
        	EntityWrapper<ConferencePerson> ew1 = new EntityWrapper<>();
    		ew1.eq("conf_id",receiveConferenceDetailVo.getConfId());  //会议ID
            
    		Integer operAmount = conferencePersonDao.selectCount(ew1);
    		receiveConferenceDetailVo.setOperAmount(operAmount);  			
			return new JsonCommon(receiveConferenceDetailVo, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
		return new JsonCommon(null, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
	}

	@Override
	public JsonForList myNotFinished(SelectConferenceModel model) {		
		//我发起的未结束的会议：待召开/进行中
		//我收到的未结束的会议：先看是否需要回执（回执不参加的去除，），待回执、待召开/进行中		
		List<MyNotFinishedConferenceVo> list = conferencePersonDao.selectMyNotFinishedConference(model.getCreateOperId());
		if (list.isEmpty()) {
			return new JsonForList(null, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		} else {
			return new JsonForList(list, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
	}

	@Override
	public JsonForList conferenceOfRoomAndDay(SelectConferenceModel model) {
		List<ConferenceRoomAppointmentVo> list = conferencePersonDao.selectConferenceOfRoomAndDay(model);
		if (list.isEmpty()) {
			return new JsonForList(null, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		} else {
			return new JsonForList(list, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
	}

	@Override
	public JsonCommon selectById(Long confId) {
		Conference conference = conferenceDao.selectById(confId);
        if (null != conference) {
			//查找参会人员数量
        	EntityWrapper<ConferencePerson> ew1 = new EntityWrapper<>();
    		ew1.eq("conf_id",conference.getConfId());  //会议ID
            
    		Integer operAmount = conferencePersonDao.selectCount(ew1);
    		conference.setOperAmount(operAmount);  
    		
    		ConferenceRoom conferenceRoom = conferenceRoomDao.selectById(conference.getConferId());
    		if (conferenceRoom != null) {
    			conference.setConferAddress(conferenceRoom.getConferAddress());
			}    		
    		return new JsonCommon(conference, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
		}
		return new JsonCommon(null, JsonCommon.SUCCESS_CODE, JsonCommon.SUCCESS_MSG);
	}

	public String toString(Object[] a) {
        if (a == null)
            return "";

        int iMax = a.length - 1;
        if (iMax == -1)
            return "";

        StringBuilder b = new StringBuilder();
        b.append("");
        for (int i = 0; ; i++) {
            b.append(String.valueOf(a[i]));
            if (i == iMax)
                return b.append("").toString();
            b.append(",");
        }
    }
}
